package com.tencent.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @BelongsProject: health
 * @BelongsPackage: com.tencent.config
 * @ClassName: SpringSecurityConfig
 * @Description: TODO
 * @Version: 1.0.0
 * @CreateTime: 2022-08-12  11:51
 * @Author: Yangjx
 */
@EnableWebSecurity//开启security
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *
     * @author Yangjx
     * @date 2022/8/12 14:28
     * @Description: TODO 密码编码器
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder(){

        return new BCryptPasswordEncoder();
    }

    /**
     * @Description: TODO
     * @author Yangjx
     * @date 2022/8/12 8:50
     * @param http
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //开跨站访问控制,且允许帧标签展示内容
        http.csrf().disable().headers().frameOptions().sameOrigin();

        http.authorizeRequests()
                //不需要登录的资源,不拦截,允许访问
                .antMatchers("/css/**","/img/**","/js/**","/plugins/**","/login.html").permitAll()
                //需要登录的资源,拦截
                .antMatchers("/**").authenticated();

        //TODO 配置访问权限   待修改！！！
        http.authorizeRequests()
                //访问某个资源需要哪个角色：     (hasRole会自动插入ROLE_)     多个权限用：hasAnyRole("",""...)
                .antMatchers("/stu/**","/setmeal/**","/showpeo/**").hasRole("ADMIN")//user.role:    ROLE_ADMIN
//                .anyRequest().hasRole("ADMIN")//待定！！！
                //TODO 给健康管理师权限     ：会员档案(刘家辉即member.html)、预约列表(leader即order_member.html)、健康评估
                .antMatchers("/member.html","/order_member.html").hasRole("HEALTH_MANAGER");//user.role:    ROLE_HEALTH_MANAGER
        //未登录,跳转到登录页
        http.formLogin()//启用form页
                .loginPage("/login.html")//登录页的URL
                .loginProcessingUrl("/login")//访问逻辑
                .permitAll();

        //无权限,跳转到无权限页面
        http.exceptionHandling().accessDeniedPage("/nopermission.html");
    }
}
